package com.tvunetworks.center.device.service.impl;


import com.tvunetworks.center.common.model.UserBehavior;
import com.tvunetworks.center.common.util.JsonUtil;
import com.tvunetworks.center.common.util.MyUtil;
import com.tvunetworks.center.device.constant.DeviceConstant;
import com.tvunetworks.center.device.mapper.UserBehaviorMapper;
import com.tvunetworks.center.device.service.UserBehaviorService;
import com.tvunetworks.center.device.service.feign.UserFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @program:
 * @description:
 * @author HenryChen
 * @create: 7/26/2019 4:02 PM
 **/
@Service
@Slf4j
public class UserBehaviorServiceImpl implements UserBehaviorService {
    @Autowired
    UserBehaviorMapper userBehaviorMapper;
    @Autowired
    private UserFeignService userFeignService;

    @Override
    public void updataUserBehavior(UserBehavior userBehavior) throws Exception{
        UserBehavior userB =  this.userBehavior(userBehavior.getUserId(), userBehavior.getPn());
        if(userB == null){
            userBehavior.setId(MyUtil.getUUID());
            userBehaviorMapper.insert(userBehavior);
        }else {
            userBehavior.setId(userB.getId());
            userBehaviorMapper.updateByPrimaryKeySelective(userBehavior);
        }
    }
    @Override
    public void updataUserBehaviorForMv(UserBehavior userBehavior) throws Exception{
//        List<UserBehavior> user =  userBehaviorMapper.selectUserBebaviorByObj(userBehavior);
        UserBehavior userBehaviorForm = new UserBehavior();
        userBehaviorForm.setPn(userBehavior.getPn());
        userBehaviorForm.setUserId(userBehavior.getUserId());
        userBehaviorForm.setRemark(userBehavior.getRemark());
        if(userBehavior.getPeerId() !=null){
            userBehaviorForm.setPeerId(userBehavior.getPeerId());
        }

       List<UserBehavior> userBf = userBehaviorMapper.select(userBehaviorForm);
       if(userBf.size()>0){
           UserBehavior userB = userBf.get(0);
           if(userB == null){
               userBehavior.setId(MyUtil.getUUID());
               userBehaviorMapper.insert(userBehavior);
           }else {
               userBehavior.setId(userB.getId());
               userBehaviorMapper.updateByPrimaryKey(userBehavior);
           }
       }else {
           userBehavior.setId(MyUtil.getUUID());
           userBehaviorMapper.insert(userBehavior);
       }

    }
    @Override
    public UserBehavior selectUserBehaviorByUid(String uid) throws Exception{
        UserBehavior userBehavior = new UserBehavior();
        userBehavior.setUserId(uid);
        return userBehaviorMapper.selectOne(userBehavior);
    }

    @Override
    public UserBehavior userBehavior(String uid, String pn) throws Exception {
        UserBehavior userBehavior = new UserBehavior();
        userBehavior.setUserId(uid);
        userBehavior.setPn(pn);
        return userBehaviorMapper.selectOne(userBehavior);
    }

    @Override
    public void setUserTimeLockBehavior(String userId, boolean sync) {
        UserBehavior record = new UserBehavior()
                .setUserId(userId)
                .setPn("hm")
                .setRemark(DeviceConstant.USER_BEHAVIOR_TIMELOCK_REMARK);
        List<UserBehavior> list = userBehaviorMapper.select(record);
        if (CollectionUtils.isEmpty(list)) {
            record.setContent(String.valueOf(sync))
                    .setId(MyUtil.getUUID())
                    .setUpdateTime(System.currentTimeMillis() + "");
            userBehaviorMapper.insert(record);
        } else {
            for (UserBehavior userBehavior : list) {
                userBehavior.setContent(String.valueOf(sync))
                        .setUpdateTime(System.currentTimeMillis() + "");
                userBehaviorMapper.updateByPrimaryKey(userBehavior);
            }
        }
    }

    @Override
    public Map<String, String> getUserBehavior(String userId, String pn) {
        UserBehavior record = new UserBehavior()
                .setUserId(userId)
                .setPn(pn);
        List<UserBehavior> list = userBehaviorMapper.select(record);
        if (CollectionUtils.isEmpty(list)) {
            return new HashMap<>();
        } else {
            Map<String, String> map = new HashMap<>();
            for (UserBehavior userBehavior : list) {
                String remark = userBehavior.getRemark();
                if (StringUtils.isBlank(remark)) {
                    continue;
                }
                if (StringUtils.equals("multiR", remark)) {
                    try {
                        String content = userBehavior.getContent();
                        if (StringUtils.isEmpty(content)) {
                            continue;
                        }
                        List<String> peerIds = userFeignService.listUserRids(userId);
                        if (CollectionUtils.isEmpty(peerIds)) {
                            log.error("getUserBehavior>>>>>>>peerIds is empty,update Contents:[{}],userId:[{}]", content, userId);
                            userBehavior.setContent(JsonUtil.toJsonStr(new ArrayList<>()));
                            userBehaviorMapper.updateByPrimaryKeySelective(userBehavior);
                            continue;
                        }
                        List<Map> contents = JsonUtil.toObject(userBehavior.getContent(), List.class);
                        if (!CollectionUtils.isEmpty(contents)) {
                            List<Map> newContents = contents.stream().filter(s -> peerIds.contains(s.get("pid").toString())).collect(Collectors.toList());
                            if (CollectionUtils.isEmpty(newContents) || newContents.size() != contents.size()) {
                                String newContent = JsonUtil.toJsonStr(newContents);
                                userBehavior.setContent(newContent);
                                userBehaviorMapper.updateByPrimaryKeySelective(userBehavior);
                            }
                        }
                    } catch (IOException e) {
                        log.error("msg:{},e:{}",e.getMessage(),e);
                    }
                }
                map.put(remark, userBehavior.getContent());
            }
            return map;
        }
    }

    @Override
    public List<UserBehavior> queryUserBehaviorByExample(UserBehavior userBehavior) {
        return userBehaviorMapper.select(userBehavior);
    }
    @Override
    public int delUserBehavior(UserBehavior userBehavior) {
        return userBehaviorMapper.delete(userBehavior);
    }
}
